package cn.zwx.admin.web.framework.handler;

import cn.hutool.core.util.ReUtil;
import cn.zwx.admin.web.common.utils.JsonUtils;
import cn.zwx.admin.web.common.utils.spring.SpringUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 获取所有Url配置
 *
 * @author zhangwenxue
 */
@Data
@Component
public class AllUrlHandler {

    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");

    public static final Logger logger = LoggerFactory.getLogger(AllUrlHandler.class);

    private static List<String> urlList = new ArrayList<>();
    public List<String>  getAllUrl() {
        if (!CollectionUtils.isEmpty(urlList)){
            return  urlList;
        }
        Set<String> set = new HashSet<>();
        RequestMappingHandlerMapping mapping = SpringUtils.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        map.keySet().forEach(info -> {
            // 获取注解上边的 path 替代 path variable 为 *
            assert info.getPathPatternsCondition() != null;
            Objects.requireNonNull(info.getPathPatternsCondition().getPatterns())
                .forEach(url -> set.add(ReUtil.replaceAll(url.getPatternString(), PATTERN, "*")));
        });
        logger.info("init all url:{}", JsonUtils.toJsonString(set));
        urlList.addAll(set);
        return new ArrayList<>(set);
    }

}
